<!-- ui model -->
<template>
  <div>
    <ToolBar @closeEvent="closeToolBar"/>
    <div class="container" :class="toolbarCloseFlag ? 'height100vh' : ''">
      <div class="cont-left">
        <el-input class="search-input" :prefix-icon="Search" v-model="filterText" placeholder="搜索"/>
        <el-tree 
          v-if="treeData.length > 0"
          ref="treeRef"
          :data="treeData" 
          :props="defaultProps"
          default-expand-all
          accordion
          node-key="id"
          highlight-current
          :current-node-key="currentNodekey"
          :filter-node-method="filterNode" 
          @node-click="clickTreeNodeHandler"
        >
        </el-tree>
      </div>
      <div class="cont-mid" ref="midBox">
        <div class="tool-bar">
          <el-button type="default" @click="clearHandler">删除</el-button>
          <el-button type="default" @click="saveHandler">保存</el-button>
        </div>
        <el-table :header-cell-style="{ background: '#161616', color: '#fff' }" class="table" v-loading="loading" :data="tableData" :height="tableHeight" style="background: #242426" :border="true">
          <el-table-column label="序号" type="index" width="60"></el-table-column>
          <el-table-column prop="sdf_field_en_name" label="字段编号" width="200">
             <template #default="scope">
              <el-input class="paperview-input-text" v-model="scope.row.sdf_field_en_name" :disabled="!scope.row.editable"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="sdf_field_zh_name" label="显示名称" width="200">
            <template #default="scope">
              <el-input v-model="scope.row.sdf_field_zh_name" :disabled="!scope.row.editable"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="数据类型" width="130">
            <template #default="scope">
              <!-- <el-select v-if="scope.row.from === 'addBtn'" v-model="scope.row.sdf_field_type" class="m-2" placeholder="Select"> -->
              <el-select v-model="scope.row.sdf_field_type" class="m-2" placeholder="Select">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.value"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="sdf_field_length" label="数据精度" width="100">
            <template #default="scope">
              <el-input v-model="scope.row.sdf_field_length" :disabled="!scope.row.editable"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="isnotnull" label="非空" width="">
            <template #default="scope">
              <el-input v-model="scope.row.isnotnull" :disabled="!scope.row.editable"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="defvalue" label="默认值" width="">
            <template #default="scope">
              <el-input v-model="scope.row.defvalue" :disabled="!scope.row.editable"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="refobject" label="关联对象" width="100">
            <template #default="scope">
              <!-- <el-input v-model="scope.row.refobject" :disabled="!scope.row.editable"></el-input> -->
              <el-input v-model="scope.row.refobject.displayName" @mousedown.native="inputKeyDownHandler(scope.row)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="生成参照" width="100">
            <template #default="scope">
              <el-checkbox style="margin-left: 40%;" v-if="scope.row.sdf_field_type === 'Guid'" v-model="scope.row.isRefer" @change="isReferChangeHandler(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button  v-if="scope.row.editable" size="small" @click="addItemHandler(scope)">+</el-button>
              <el-button  v-if="scope.row.editable" size="small" @click="deleteItemHandler(scope)">-</el-button>
            </template>
          </el-table-column>
        </el-table >
      </div>
      <div class="cont-right" ref="rightBox">
        <div class="group refer-box">
          <el-collapse v-model="activeTabName">
            <el-collapse-item title="关联对象" name="关联对象">
              <div class="custom-tree-node">
                <div class="tree-head"><img class="icon" src="../../assets/images/uiModel/icon-group.png" alt="">reference</div>
                <div class="tree-body">
                  <draggable
                    v-model="referObjTreeData"
                    :sort="false"
                    :onEnd="dragReferTreeHandler"
                    item-key="id">
                    <template #item="{element}">
                      <p class="drag-item"><img class="icon" src="../../assets/images/uiModel/icon-referobj.png" alt="">{{element.sdt_table_zh_name}}</p>
                    </template>
                  </draggable>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <div class="group object-box">
          <el-collapse v-model="activeTabName">
            <el-collapse-item title="对象" name="对象">
              <div class="obj-btn-wrap">
                <draggable
                  class="drag-box"
                  v-model="objectArr"
                  :sort="false"
                  :onEnd="dragObjectHandler"
                  item-key="id">
                  <template #item="{element}" >
                    <div class="btn-item">
                      <img class="icon" src="../../assets/images/uiModel/icon-child-obj.png"/>
                      <div class="btn">{{element.name}}</div>
                      <!-- <el-button class="btn" type="default">{{element.name}}</el-button> -->
                    </div>
                  </template>
                </draggable>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <div class="group filed-box">
          <el-collapse v-model="activeTabName">
            <el-collapse-item title="基础字段" name="基础字段">
              <draggable
                v-model="btnArry"
                :sort="false"
                :onEnd="dragFieldHandler"
                item-key="id">
                <template #item="{element}">
                  <div class="drag-item">
                    <!-- <img class="icon" :src="`../../assets/images/uiModel/${element.icon_name}.png`"/> -->
                    <img class="icon" :src="getImg(element.icon_name)"/>
                    <span class="text">{{element.name}}</span>
                  </div>
                </template>
              </draggable>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      width="30%"
      >
      <span>是否保存文件</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSaveHandler">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="deleteDialogVisible"
      width="30%"
      >
      <span>是否删除</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDeleteHandler">删除</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      :title="referTableTitle"
      v-model="referTableDialogVisible"
      >
      <el-table :data="referTableData" :height="400" @row-click="handleSelectionChange">
        <el-table-column>
          <template #default="scope">
            <el-radio v-model="templateSelection" :label="scope.$index">&nbsp;</el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="sdf_field_en_name" label="字段编号" width="200"></el-table-column>
        <el-table-column prop="sdf_field_zh_name" label="显示名称" width="200"></el-table-column>
        <el-table-column prop="sdf_field_type" label="数据类型" width="130"></el-table-column>
      </el-table>
      <el-footer>
        <el-button @click="confirmReferTableHandler">确定</el-button>
      </el-footer>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import draggable from 'vuedraggable'
import ToolBar from '@/components/ToolBar/index.vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { reactive, ref, watch, nextTick, onMounted, watchEffect } from 'vue';
import { getWorkSysApi, getTableNameApi, getSysTableFieldApi, savaScriptApi, getTableInfoApi } from '@/api/uiModel';
import { uuid } from 'vue3-uuid'
import { useRoute, useRouter } from 'vue-router';

const router = useRouter()
const route = useRoute()

const toolbarCloseFlag = ref(false) //toolbar是否关闭掉
const rightBox = ref(null)
const midBox = ref(null)
const loading = ref(false)
const activeTabName = reactive(['关联对象', '对象', '基础字段'])
const fileName = "主表名字"
let currenTableName = '' // 当前table类型 [主，子，孙]
const moduleid = '123' // 所选系统的id，需要添加到每一个列数据里面；如果新建表该字段为空
const dialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const referTableDialogVisible = ref(false)
const tableHeight = ref(0)

const crateInfoStr:any = localStorage.getItem('createInfo')
const crateInfo = JSON.parse(crateInfoStr)

const filterText = ref('')
const treeRef = ref()
let defaultProps = {
  label: 'label',
  children: 'children',
}
let currentNodekey = reactive({})

const tableData = ref([
  // {
  //   field_code: '',
  //   field_name: '',
  //   data_type: '',
  //   data_length: '255',
  //   is_must: '',
  //   defalut_val: '',
  //   object: ''
  // }
])
const referTableTitle = ref()
const referTableData = ref([])
const templateSelection = ref(-1)
const currentReferRow = ref({}) // 点击当前refer的row数据

interface Tree {
  label: string,
  children?: Tree[]
}

const options = [
  {
    value: 'Guid',
    label: '对象主键',
  },{
    value: 'String',
    label: '字符串',
  },{
    value: 'Int',
    label: '整型',
  },{
    value: 'Double',
    label: 'Double数值型',
  },{
    value: 'Float',
    label: 'Float数值型',
  },{
    value: 'Date',
    label: '日期',
  },{
    value: 'Time',
    label: 'Time时间',
  },{
    value: 'String',
    label: 'String字符串',
  },{
    value: 'Guid',
    label: 'Guid对象主键',
  },{
    value: 'Text',
    label: '大文本',
  }
]

let treeData = ref([])

let referObjTreeData = ref([
  // {
  //   label: '组织机构',
  //   children: [
  //     {
  //       label: '关联对象2',
  //       id: 1
  //     },{
  //       label: '关联对象3',
  //       id: 2
  //     },{
  //       label: '关联对象4',
  //       id: 3
  //     }
  //   ]
  // }
])
// 对象集合
const objectArr = reactive([
  { name: '主对象', id: 1},
  { name: '子对象', id: 2}
])
// 字段集合
const btnArry = reactive([
    { name: "对象主键", id: 1, sdf_field_type: 'Guid',icon_name:'icon-main-key', },
    { name: "字符串", id: 2, sdf_field_type: 'String',icon_name:'icon-string', },
    { name: "整型", id: 3, sdf_field_type: 'Int',icon_name:'icon-int', },
    { name: "Double数值型", id: 4, sdf_field_type: 'Double',icon_name:'icon-double', },
    { name: "Float数值型", id: 5, sdf_field_type: 'Float',icon_name:'icon-float', },
    { name: "日期", id: 6, sdf_field_type: 'Date',icon_name:'icon-date', },
    { name: "Time时间", id: 7, sdf_field_type: 'Time',icon_name:'icon-time', },
    { name: "String字符串", id: 8, sdf_field_type: 'String',icon_name:'icon-string', },
    { name: "Guid对象主键", id: 9, sdf_field_type: 'Guid',icon_name:'icon-guid', },
    { name: "大文本", id: 10, sdf_field_type: 'Text',icon_name:'icon-string', },
  ])

const dataMap:{[k: string]: string} = reactive({
  'string': '字符串类型',
})


// 主对象默认数据
const mainObjData = ref([
  {sdf_field_en_name: 'Pkey', sdf_field_zh_name: '主键', sdf_field_type: 'Guid', editable: false, sdf_field_length: 36, isnotnull: true, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'Code', sdf_field_zh_name: '编码', sdf_field_type: 'String' , editable: false, sdf_field_length: 36, isnotnull: true, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'Group_id', sdf_field_zh_name: '集团', sdf_field_type: 'Guid', editable: false, sdf_field_length: 36, isnotnull: true, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'Org_id', sdf_field_zh_name: '组织', sdf_field_type: 'Guid', editable: false, sdf_field_length: 36, isnotnull: true, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'Branch_id', sdf_field_zh_name: '院区', sdf_field_type: 'Guid', editable: false, sdf_field_length: 36, isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'workflow', sdf_field_zh_name: '工作流', sdf_field_type: 'Guid', editable: false, sdf_field_length: 36, isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'def1', sdf_field_zh_name: '自定义字段1', sdf_field_type: 'String', editable: true, sdf_field_length: 100, isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'def2', sdf_field_zh_name: '自定义字段2', sdf_field_type: 'String', editable: true, sdf_field_length: 100, isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'def3', sdf_field_zh_name: '自定义字段3', sdf_field_type: 'String', editable: true, sdf_field_length: 100, isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'def4', sdf_field_zh_name: '自定义字段4', sdf_field_type: 'String', editable: true, sdf_field_length: 100, isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'def5', sdf_field_zh_name: '自定义字段5', sdf_field_type: 'String', editable: true, sdf_field_length: 100, isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'def6', sdf_field_zh_name: '自定义字段6', sdf_field_type: 'String', editable: true, sdf_field_length: 100, isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'def7', sdf_field_zh_name: '自定义字段7', sdf_field_type: 'String', editable: true, sdf_field_length: 100, isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'def8', sdf_field_zh_name: '自定义字段8', sdf_field_type: 'String', editable: true, sdf_field_length: 100, isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'def9', sdf_field_zh_name: '自定义字段9', sdf_field_type: 'String', editable: true, sdf_field_length: 100, isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'def10', sdf_field_zh_name: '自定义字段10', sdf_field_type: 'Double', editable: true, sdf_field_length: '28,8', isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'def11', sdf_field_zh_name: '自定义字段11', sdf_field_type: 'Double', editable: true, sdf_field_length: '28,8', isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'def12', sdf_field_zh_name: '自定义字段12', sdf_field_type: 'Double', editable: true, sdf_field_length: '28,8', isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'Creater', sdf_field_zh_name: '创建人', sdf_field_type: 'Guid', editable: false, sdf_field_length: 36, isnotnull: true, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'CreateOn', sdf_field_zh_name: '创建时间', sdf_field_type: 'DateTime', editable: false, sdf_field_length: 19, isnotnull: true, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'Modifier', sdf_field_zh_name: '修改人', sdf_field_type: 'Guid', editable: false, sdf_field_length: 36, isnotnull: true, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'ModifiedOn', sdf_field_zh_name: '修改时间', sdf_field_type: 'DateTime', editable: false, sdf_field_length: 19, isnotnull: true, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'Ts', sdf_field_zh_name: '时间戳', sdf_field_type: 'DateTime', editable: false, sdf_field_length: 19, isnotnull: true, defvalue: '', refobject: ''},
])
// 子对象默认数据
const childObjData = ref([
  {sdf_field_en_name: 'Pkey', sdf_field_zh_name: '主键', sdf_field_type: 'Guid',editable: false, sdf_field_length: 36, isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'Code', sdf_field_zh_name: '编码', sdf_field_type: 'String',editable: false, sdf_field_length: 36, isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'parentKey', sdf_field_zh_name: '父键', sdf_field_type: 'Guid',editable: false, sdf_field_length: 36, isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'def1', sdf_field_zh_name: '自定义字段1', sdf_field_type: 'String',editable: true, sdf_field_length: 36, isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'def2', sdf_field_zh_name: '自定义字段2', sdf_field_type: 'String',editable: true, sdf_field_length: 36, isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'def3', sdf_field_zh_name: '自定义字段3', sdf_field_type: 'String',editable: true, sdf_field_length: 36, isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'def4', sdf_field_zh_name: '自定义字段4', sdf_field_type: 'Double',editable: true, sdf_field_length: 36, isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'def5', sdf_field_zh_name: '自定义字段5', sdf_field_type: 'Double',editable: true, sdf_field_length: 36, isnotnull: false, defvalue: '', refobject: ''},
  {sdf_field_en_name: 'def6', sdf_field_zh_name: '自定义字段6', sdf_field_type: 'Double',editable: false, sdf_field_length: 36, isnotnull: false, defvalue: '', refobject: ''},
]);

// 拖动对象
const dragObjectHandler = function(element: Object) {
  const oldIndex = (element as any)?.oldIndex;
  const name = objectArr[oldIndex].name;
  if (name === '主对象') {
    if (tableData.value.length > 0) {
      return
    }
    currenTableName = '主表';
    const UUID = uuid.v4();
    sessionStorage.setItem('PARENT_UUID', UUID);
    (tableData as any).value = mainObjData.value
  } else if (name === '子对象') {
    // 如果已经存在主对象，需要弹窗提示，是否确认覆盖主对象
    if(tableData.value.length > 0 && currenTableName.indexOf('主表') > -1) {
      ElMessageBox.confirm(
       '是否保存主表?',
        'Warning',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false
        },
      )
      .then( async () => {
        await saveHandler()
        currenTableName = '子表';
        const UUID = uuid.v4();
        sessionStorage.setItem('CHILD_UUID', UUID);
        (tableData as any).value = childObjData.value
      })
    } else if (tableData.value.length > 0 && currenTableName == '子表') {
      ElMessageBox.confirm(
        '覆盖子对象数据,并清空?',
        'Warning',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false
        },
      )
      .then(() => {
        currenTableName = '孙表';
        (tableData as any).value = childObjData.value
      })
    } else if (tableData.value.length = 0) {
      return
    }
  }
  const clientX = (element as any)?.originalEvent.clientX;
  const midBoxElement = midBox
  console.log(midBox)
  // ElMessage.success(`拖动对象${name},拖动到X坐标${clientX}处`)
}
// 拖动字段
const dragFieldHandler = function(element: Object) {
  // console.log((rightBox as any).value.offsetLeft)
  // console.log(element)
  // console.log('拖动结束', btnArry[(element as any)?.oldIndex].name);
  if (!(tableData as any).value.length) return
  let data = {
    sdf_field_en_name: '',
    sdf_field_zh_name: '',
    sdf_field_length: 36,
    isnotnull: false,
    defvalue: '',
    refobject: '',
    sdf_field_type: btnArry[(element as any)?.oldIndex].sdf_field_type,
    from: 'dragBtn',
    editable: true
  }
  const index = tableData.value.length - 5;
  (tableData as any)?.value.splice(index, 0, data)
}
// 增加table行
const addItemHandler = function(element: Object) {
  const index = (element as any)?.$index;
  const currentRow = (element as any).row;
  const obj = Object.assign({}, currentRow);
  obj.from = 'addBtn'
  console.log('add====', obj);
  // (tableData as any)?.value.push(obj)
  (tableData as any)?.value.splice(index+1, 0, obj)
}
// 删除table行
const deleteItemHandler = function(element: Object) {
  const index = (element as any)?.$index;
  const newArr = (tableData as any)?.value.filter((item, idx) => idx != index);
  tableData.value = newArr
}
// 点击左边树节点
const clickTreeNodeHandler = function(e: object) {
  const target = (e as any)
  const label = target.label;
  currenTableName = label;
  if (crateInfo && label === crateInfo.modelZhName) return // 点击当前tree，如果是新创建的，不用去调接口重置table数据
  // if(target.hasOwnProperty('children')) return;
  // getTableName(target.code)
  console.log(e)
  if(target.reference?.length > 0) {
    referObjTreeData.value = target.reference
  }
  tableData.value = target.fields
  return false
}
// 拖拽关联对象
const dragReferTreeHandler = function(element: Object) {
  const target = element as any;
  console.log(target)
  referTableDialogVisible.value = true;
  templateSelection.value = -1
  referTableData.value = (referObjTreeData.value[target.oldIndex] as any).fields
  referTableTitle.value = `参照-${(referObjTreeData.value[target.oldIndex] as any).sdt_table_zh_name}`
}

const handleSelectionChange = (e) => {
  templateSelection.value = (referTableData.value as any)?.indexOf(e)
}

const confirmReferTableHandler = () => {
  if (templateSelection.value === -1) return
  referTableDialogVisible.value = false;
  const selectIndex = templateSelection.value
  const selectRowObj = (referTableData.value as any)[selectIndex]
  console.log(selectIndex, selectRowObj);
  const pkname = referTableData.value.filter((ele) => (ele as any).sdf_primary_key == 'NO')[0];
  console.log('referTableData.value======', referTableData.value)
  console.log('pkname======', pkname)
  const obj = {
    pkName: (pkname as any).sdf_field_en_name,
    fieldName: (selectRowObj as any).sdf_field_en_name,
    displayName: (selectRowObj as any).sdf_field_zh_name,
    tableName: (selectRowObj as any).sdt_table_en_name
  };
  (currentReferRow.value as any).refobject = obj
  console.log(currentReferRow.value)
}

const inputKeyDownHandler = (e) => {
  const row = e as any;
  currentReferRow.value = row
  console.log(currentReferRow)
}

const isReferChangeHandler = (e) => {
  const row = e as any;
  console.log(currentReferRow)
}

const clearHandler = function() {
  if(!tableData.value.length) return
  deleteDialogVisible.value = true
}
const confirmDeleteHandler = function() {
  deleteDialogVisible.value = false
  tableData.value = []
}

const saveHandler = async function() {
  if (!tableData.value.length) return
  const data = tableData.value
  // const flag = validateTable(data)
  // console.log(flag)
  // if(flag) {
  //   dialogVisible.value = true
  // }
  dialogVisible.value = true
}

const confirmSaveHandler = function() {
  // tableData.value.map(ele => {
  //   (ele as any).moduleid = moduleid
  //   return ele
  // })
  let fileName = `${currenTableName}.json`
  let DomainModel = {}
  if (currenTableName.indexOf('主表') > -1) {
    const uuid = sessionStorage.getItem('PARENT_UUID')
    DomainModel = {
      sdt_id: "4dc062ad-3ebb-4f0f-a45e-1f64b3127daf",
      sdt_system_name: crateInfo.solutionName,
      sdt_table_type: "TABLE",
      sdt_table_zh_name: crateInfo.modelZhName,
      sdt_table_en_name: crateInfo.modelEnName,
      sdt_create_date: new Date(),
      sdt_creater: "系统管理员",
      sdt_pid: null,
      sdt_index: null,
      search_condition: null,
      res_code: null,
      classpatch: null,
      memo: null,
      type: 1,
      sort: null,
      groupcode: null,
      systable: null,
      addfield: null,
      tcid: null,
      sptid: null,
      createon: new Date(),
      modifier: '系统管理员',
      modifiedon: new Date(),
      moduleid: null,
    }
  }
  if (currenTableName.indexOf('子表') > -1) {
    const pid = sessionStorage.getItem('PARENT_UUID')
    const uuid = sessionStorage.getItem('CHILD_UUID')
    DomainModel = {
      sdt_id: "d8eb3daa-952e-42b3-ba0d-cd0cd77ea393",
      sdt_system_name: "hr",
      sdt_table_type: "TABLE",
      sdt_table_zh_name: "还欠款方案规则业务控制",
      sdt_table_en_name: "HR_ARREARS_RULES_BUSINESS",
      sdt_create_date: new Date(),
      sdt_creater: "系统管理员",
      sdt_pid: '4dc062ad-3ebb-4f0f-a45e-1f64b3127daf',
      sdt_index: null,
      search_condition: null,
      res_code: null,
      classpatch: null,
      memo: null,
      type: 0,
      sort: null,
      groupcode: null,
      systable: null,
      addfield: null,
      tcid: null,
      sptid: null,
      createon: new Date(),
      modifier: '系统管理员',
      modifiedon: new Date(),
      moduleid: null
    }
  }
  const result = {
    ...DomainModel,
    fields: formatTableKey(tableData.value, DomainModel)
  }
  let jsonData = JSON.stringify(result)
  saveFileFunction(fileName, jsonData)
  dialogVisible.value = false
}

// table字段校验
const validateTable = function(data: Array<any>) {
   // 非空校验
  const enNameIsNull = data.some(ele => (ele as any).sdf_field_en_name == '')
  const zhNameIsNull = data.some(ele => (ele as any).sdf_field_zh_name == '')
  const lengthIsNull = data.some(ele => (ele as any).sdf_field_length == '')
  const exsitIsNull = data.some(ele => (ele as any).isnotnull+'' == '')
  const valIsNull = data.some(ele => (ele as any).defvalue == '')
  const refIsNull = data.some(ele => (ele as any).refobject == '')
  const typeIsNull = data.some(ele => (ele as any).sdf_field_type == '')
  if (enNameIsNull || zhNameIsNull || lengthIsNull || exsitIsNull || valIsNull || refIsNull || typeIsNull){
    ElMessage.error('数据不能为空！')
    return false
  }
  // 重复值校验 (字段编号，显示名称不能重复)
  let repeatFlag = false
  let index1, index2, tag
  for (let i = 0; i<data.length; i++) {
    for(let j = i+1; j<data.length; j++) {
      if((data[i] as any).sdf_field_en_name == (data[j] as any).sdf_field_en_name) {
        repeatFlag = true
        index1 = i
        index2 = j
        tag = '字段编号' 
        break
      }
      // if((data[i] as any).sdf_field_zh_name == (data[j] as any).sdf_field_zh_name) {
      //   repeatFlag = true
      //   index1 = i
      //   index2 = j
      //   tag = '显示名称'
      //   break
      // }
    }
  }
  if (repeatFlag){
    ElMessage.error(`第${index1+1}与第${index2+1}行${tag}重复！`)
    return false
  } 
  return true
}

// table字段的keyformat
const formatTableKey = function(data: Array<any>, DomainModel: any) {
  if(!data.length) return
  const UUID = currenTableName === '主表' ? sessionStorage.getItem('PARENT_UUID') : sessionStorage.getItem('CHILD_UUID')
  const arr =  data.map((ele, idx) => {
    ele.sdt_system_name = DomainModel.sdt_system_name;
    ele.sdt_table_en_name = DomainModel.sdt_table_en_name;
    ele.sdt_id = DomainModel.sdt_id
    ele.version = ele.version == null ? '3.1': ele.version
    ele.isextend = ele.from === 'dragBtn' ? true : false
    return ele
  })
  return arr
}

// 保存JSON到本地
const saveFileFunction = (fileName: string, data: string) => {
  let element = document.createElement('a')
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(data));
  element.setAttribute('download', fileName);
  if (document.createEvent) {
        let event = document.createEvent('MouseEvents');
        event.initEvent('click', true, true);
        element.dispatchEvent(event);
    } else {
        element.click();
    }
}

const filterNode = function(value: string, data: Tree) {
  if (!value) return true
  return data.label?.includes(value)
}

// 获取左侧tree数据
const getLeftTreeData = async () =>{
  const result = await getWorkSysApi()
  const obj: any = localStorage.getItem('createInfo')
  const createInfo = JSON.parse(obj)
  console.log('createInfo', createInfo)
  const solutionName = createInfo.solutionName
  const moduleName = createInfo.moduleName
  const modelZhName = createInfo.modelZhName
  let currentId;
  let list = result.data.map(ele => {
    // if (ele.value === solutionName) {
    //   ele.children.map(e => {
    //     if(e.value === moduleName) {
    //       if(!e.children) {
    //         e.children = []
    //       }
    //       e.children.push({
    //         label: modelZhName,
    //         value: modelZhName,
    //         id: ''
    //       })
    //       currentId = e.children
    //     }
    //     return e
    //   })
    // }
    return ele
  })
  list = treeFormat(list)
  treeData.value = list
  // treeData.value = list.filter(ele => ele.value === solutionName)
  // 设置高亮节点
  nextTick(() => {
    treeRef.value.setCurrentKey(currentId[0].id)
  })
}

// 获取table数据 
const getTableInfo = async () => {
  const result = await getTableInfoApi()
  const data = [result?.data]
  const fomData = treeFormat(data)
  console.log('tableInfo====', fomData);
  (treeData as any).value = fomData
}
// 获取表名
const getTableName = async function(code: string) {
  const result = await getTableNameApi(code)
  const list = result.data
  console.log('查询表的结果====', list)
  if (!list.length) {
    tableData.value = []
    return ElMessage.error('查询到表数据值为空')
  }
  loading.value = true
  const originData = await getTableField(list[0].sdt_table_en_name)
  loading.value = false
  tableData.value = (originData as any)
  console.log('表对应字段的数据====', originData)
}
// 获取table默认字段
const getTableField = async function(tablename: string) {
  const result = await getSysTableFieldApi(tablename)
  const list = result.data
  return list
}
const initData = () => {
  const UUID = uuid.v4();
  sessionStorage.setItem('PARENT_UUID', UUID);
  (tableData as any).value = mainObjData.value
  currenTableName = `主表-${crateInfo.modelZhName}`
}

// 获取系统业务dataList
// getLeftTreeData()
// initData()

getTableInfo()



// tree 数据格式化 label
const treeFormat = function(data: any[]) {
  if (!data || !data.length) return
  for (let i = 0; i < data.length; i++) {
    if (data[i].children) {
      data[i].label = data[i].value
      // data[i].label = data[i].sdt_table_zh_name
      treeFormat(data[i].children)
    } else {
      data[i].label = data[i].value
      // data[i].label = data[i].sdt_table_zh_name
    }
  }
  return data
}

const closeToolBar = () => {
  toolbarCloseFlag.value = true
  nextTick(() => {
    const { height } = (midBox.value as any)?.getBoundingClientRect();
    console.log(height)
    tableHeight.value = height - 35
  })
}

const modules = import.meta.globEager('/src/assets/images/uiModel/*')
console.log("modules", modules)
const getImg = (imgName: string) => {
  const path = `/src/assets/images/uiModel/${imgName}.png`
  return modules[path].default
}

onMounted(() => {
    const { height } = (midBox.value as any)?.getBoundingClientRect();
    tableHeight.value = height - 35
    console.log(tableHeight.value)
})




watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
</script>
<style lang='scss' scoped>
// @import '../../styles/table.scss';
.height100vh {
  height: 100vh !important;
}
.container {
  // overflow: hidden;
  height: calc(100vh - 50px);
  display: flex;
  overflow-y: scroll;
  .cont-left {
    width: 15%;
    background: #242426;
    border-right: 1px solid #000;
    overflow-y: scroll;
    .search-input {
      ::v-deep(.el-input__wrapper) {
        background-color: #1e1e1e;
      }
    }
  }
  .cont-right {
    overflow-y: scroll;
    width: 15%;
    background: #242426;
    border-left: 1px solid #000;
    .group {
      display: flex;
      flex-direction: column;
      .btn {
        margin: 5px 0;
      }
    }
    .refer-box {
      .custom-tree-node {
        color: #fff;
        .tree-head {
          display: flex;
          align-items: center;
          margin: 5px 0;
          padding-left: 10px;
          height: 32px;
          line-height: 32px;
          background: #3B3B3B;
          .icon {
            margin-right: 5px;
            width: 20px;
            height: 20px;
          }
        }
        .tree-body {
          padding-left: 30px;
          .drag-item {
            position: relative;
            display: flex;
            align-items: center;
            margin-bottom: 5px;
            padding-left: 10px;
            width: 150px;
            height: 32px;
            line-height: 32px;
            background: #3B3B3B;
            border-radius: 2px 2px 2px 2px;
            cursor: pointer;
            .icon {
              margin-right: 5px;
              width: 20px;
              height: 20px;
            }
            &::before {
              position: absolute;
              left: -10px;
              top: 16px;
              content: "";
              width: 10px;
              height: 1px;
              border-bottom: 1px dashed #A5A5A5;
            }
            &::after {
              position: absolute;
              left: -10px;
              content: "";
              width: 1px;
              height: 32px;
              border-left: 1px dashed #A5A5A5;
            }
          }
        }
      }
    }
    .object-box {
      .obj-btn-wrap {
        .drag-box {
          margin: 8px 0 3px;
          display: flex;
          justify-content: space-around;
          .btn-item {
            display: flex;
            width: 45%;
            align-items: center;
            justify-content: center;
            border-radius: 2px;
            background-color: #2E2E2E;
            cursor: pointer;
            .icon {
              margin-right: 5px;
              width: 20px;
              height: 20px;
            }
            .btn {
              height: 20px;
              color: #F6F8FA;
              word-break: keep-all;
            }
          }
        }
        
      }
    }
    .filed-box {
      .drag-item {
        display: flex;
        align-items: center;
        margin: 5px;
        padding-left: 14px;
        height: 32px;
        font-size: 16px;
        color: #000000;
        background-color: #D9E2EB;
        border-radius: 4px;
        cursor: pointer;
        .icon {
          display: block;
          width: 16px;
          height: 16px;
        }
        .text {
          margin-left: 10px;
          word-break: keep-all;
        }
      }
      .btn {
        width: 100%;
        color: #000000;
        background-color: #D9E2EB;
      }
    }
  }
  .cont-mid {
    flex: 1;
    overflow-x: scroll;
    background: #353535;
    .tool-bar {
      height: 30px;
      display: flex;
      flex-direction: row-reverse;
    }
  }
}
</style>

<style lang="scss">
// @import '../../styles/table.scss';
// table样式重写
.table {
  color: #fff;
  border-color: #303030 !important;
  tr {
    &:nth-child(even) {
      background-color:  #3B4046 ;
      .el-input__wrapper{
        background-color: #3B4046;
      }
    }
    &:nth-child(odd) {
      background-color: #6D6D6D;
      .el-input__wrapper{
        background-color: #6D6D6D;
      }
    }
    &:hover {
      td {
        background: #006FFF !important;
      }
      .el-input__inner {
        background: #006FFF;
      }
    }
  }
  .el-input__wrapper {
    box-shadow: none;
  }
  .el-input__inner {
    color: #fff;
    &:focus {
      background: #2E4B6B !important;
      border: 1px solid #006FFF;
    }
  }
  tbody {
    .el-table__cell {
      padding: 0;
      border-color: #D2D1D1 !important;
      transition: none !important; // 背景色过度延迟bug
      .cell {
        padding: 0;
        .el-input__wrapper {
          padding: 0;
        }
      }
    }
  }
  .el-table__empty-block {
    background: #303030;
  }
  .el-input.is-disabled {
    .el-input__wrapper {
      box-shadow: none;
    }
  }
}
</style>